package com.bayi.program;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * @author Administrator on 2025-05-14.
 * <p>
 * 站在顶峰 看世界
 * 落到谷底 思人生
 */
public class ProgramListeningSingle {

    /**
     * 包名
     */
    public static final String PACKAGE_NAME = "com.example.wujia.compactshelves";

    private static final String TAG = ProgramListeningSingle.class.getSimpleName();
    private volatile static ProgramListeningSingle instance = null;

    public static ProgramListeningSingle getInstance() {
        if (instance == null) {
            synchronized (ProgramListeningSingle.class) {
                if (instance == null) {
                    instance = new ProgramListeningSingle();
                }
            }
        }
        return instance;
    }

    public void startHandler() {
        handler.removeCallbacks(runnable);
        handler.postDelayed(runnable, 5 * 60 * 1000);
        handler30.removeCallbacks(runnable30);
        handler30.postDelayed(runnable30, 30 * 60 * 1000);
    }


    private Handler handler = new Handler(Looper.getMainLooper());
    private Runnable runnable = () -> {
//        new Thread(() -> {
//            ShellUtils.CommandResult commandResult = ShellUtils.execCommand(new ArrayList<>(Arrays.asList("su", "0", "reboot")), true);
//        }).start();
        restartApp(BaseApplication.getApp());

        startHandler();
        Log.e("TimeChangeReceiver", "5分钟没收到数据");
    };

    private Handler handler30 = new Handler(Looper.getMainLooper());
    private Runnable runnable30 = () -> {
        new Thread(() -> {
            ShellUtils.CommandResult commandResult = ShellUtils.execCommand(new ArrayList<>(Arrays.asList("su", "0", "reboot")), true);
        }).start();
        Log.e("TimeChangeReceiver", "30分钟没收到数据");
    };

    public void restartApp(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

        // 结束目标应用的进程
        am.killBackgroundProcesses(PACKAGE_NAME);

        // 启动应用的主Activity
        Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(PACKAGE_NAME);
        if (launchIntent != null) {
            launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(launchIntent);
        }
    }

}
